<template>
	<div ref="chartDom" class="chart" v-if="name.length>0">
	</div>
	<h3 v-else>
		暂无数据
	</h3>
</template>

<script>
	import * as echats from 'echarts';
	import {defineComponent,ref,computed,onMounted} from 'vue';
	
	//返回 数组中 元素出现次数
	function statistics(arr,item){
		var obj={}
		arr.forEach(list=>{
				if(list[item]!=null)
				if(obj[list[item]] != null){
					obj[list[item]]+=1;
				}else{
					obj[list[item]]=1;
				}
		})
		return obj;
	}
	export default defineComponent({
		props:{
			Data:{
				type:Array,
				default:[]
			}
		},
		setup(props){
				let chartDom=ref()
				//获取各类商品个数
				let classes=statistics(props.Data,'genre');
				var value=[]
				var name=[]
				for(var key in classes){
					name.push(key);
					value.push(classes[key])
				}
				onMounted(()=>{
					console.log('onMounted',chartDom.value)
					if(name.length>0)
					render(chartDom.value,name,value)
				})
				return{
					value,
					name,
					classes,
					chartDom
				}
			
		}
	})
	//渲染echats
	function render(chartDom,name,value){
		var myChart = echats.init(chartDom);
		var option;
		
		option = {
		  xAxis: {
		    type: 'category',
		    data: name
		  },
		  yAxis: {
		    type: 'value',
				minInterval: 1 
		  },
		  series: [
		    {
		      data: value,
		      type: 'bar',
		      showBackground: true,
		      backgroundStyle: {
		        color: 'rgba(180, 180, 180, 0.2)'
		      }
		    }
		  ]
		};
		window.addEventListener("resize",function() {
		        myChart.resize();
		});
		option && myChart.setOption(option);
	}
</script>

<style>
	.chart{
		width:90vw;
		height: 50vh;
		margin: 0 auto;
	}
</style>
